package io;

import java.io.*;
import java.util.Random;

/**
 * 对象输入输出流
 *
 * 对象流
 * java.io.ObjectOutputStream 和 java.io.ObjectInputStream
 * 对象流是一对高级流，作用是进行对象的序列化与反序列化
 *
 * 在进行对象IO操作时需要对象的类实现 Serializable 接口，无需重写方法，只是进行一个标记
 * */
public class ObjectInputOutputStreamDemo {
    private static Person[] getPerson(int n) {
        Person[] persons = new Person[n];
        Random random = new Random();
        for (int i = 0; i < n; i++)
            persons[i] = new Person("name" + (i + 1), random.nextInt(20) + 18,
                    random.nextInt(2) == 1 ? "男" : "女",
                    new String[]{"电话：" + (random.nextInt((int)Math.pow(10, 8)) +
                            (random.nextInt(100) + 110) * (long)Math.pow(10, 8)),
                            "qq：" + (random.nextInt((int)Math.pow(10, 9)) +
                                    (random.nextInt(10) + 1) * (int)Math.pow(10, 8))});
        return persons;
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Person[] persons = getPerson(10);
        String filename = "files/person.obj";
        ObjectOutputStream objOut = new ObjectOutputStream(new FileOutputStream(filename));
        for (Person person : persons)
            objOut.writeObject(person);
        objOut.close();
        ObjectInputStream objIn = new ObjectInputStream(new FileInputStream(filename));
        while (true) {
            try {
                Person person = (Person) objIn.readObject();
                System.out.println(person + "\n\n");
            } catch (EOFException e) {
                break;
            }
        }
        objIn.close();
    }
}
